import { defineStore } from "pinia";
import cookie from "js-cookie";
import router from "@/router";
import { ElMessage } from "element-plus";
import { post } from "@/http/request";

export const useUserStore = defineStore({
    id: "useUserStore",
    persist: true, //持久化
    state: () => ({
        user: new UserInfo(), //用户信息
    }),
    getters:{
        /**
         * 用户权限列表
         * @param state 状态管理仓库
         * @returns 权限列表
         * */ 
        permissionList:(state) => {
            return state.user.perms
        }
    },
    actions: {
        // 设置用户信息
        setUser(user: UserInfo) {
            this.user = user;
        },
        // 退出登录
        logout() {
            let that = this
            let data = {
                _gp: "admin",
                _mt: "logout",
            }
            post( data).then(res => {
                // console.log(res);
                let { errno, errmsg } = res
                if (200 == errno) {
                    that.user = new UserInfo()
                    cookie.remove("token")
                    router.replace("/login")
                    ElMessage.success('退出成功')
                }else{
                    ElMessage.error(errmsg)
                }
            })
        }
    }
});

class UserInfo {
    avatarUrl?: string;
    gmtCreate: number;
    gmtLastLogin: string;
    gmtUpdate: number;
    id: number;
    lastLoginIp: string;
    perms: string[];
    phone: string;
    realname: string;
    roleIds: number[];
    roles: string[];
    status: number;
    username: string;
    password:string;
    constructor() {
        this.avatarUrl = "";
        this.gmtCreate = 0;
        this.gmtLastLogin = "";
        this.gmtUpdate = 0;
        this.id = 0;
        this.lastLoginIp = "";
        this.perms = [];
        this.phone = "";
        this.realname = "";
        this.roleIds = [];
        this.roles = [];
        this.status = 0;
        this.username = "";
        this.password = "";
    }
}

